import "./DialoguePanel.css"
import { memo, useState, useRef, useEffect } from 'react'
import useStore from '@/store';

import MarkdownRenderer from '@/components/MarkdownRenderer'

import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import ContentCopyOutlinedIcon from '@mui/icons-material/ContentCopyOutlined';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import RefreshOutlinedIcon from '@mui/icons-material/RefreshOutlined';


const AssistantMessage = memo(({ index, content, handleDeleteMessage, handleCopyMessage, editingMessageIndex }) => {
    // console.log('AssistantMessage');
    const isEditingOtherMessage = editingMessageIndex !== null;

    return (
        <div className="assistant-message-block" >
            <div>
                <MarkdownRenderer content={content} />
            </div>
            <div className="dialogue-panel-message-action-bar" style={{ position: 'relative', left: '-8px' }}>
                <div onClick={() => { handleCopyMessage(content) }}><ContentCopyOutlinedIcon fontSize="" /></div>
                <div onClick={() => { if (!isEditingOtherMessage) handleDeleteMessage(index) }}><DeleteOutlinedIcon fontSize="small" /></div>
            </div>
        </div>
    );
});

const UserMessage = ({ index, content, handleDeleteMessage, handleCopyMessage, uuid, editingMessageIndex, setEditingMessageIndex }) => {

    const textareaRef = useRef(null);
    const updateDialogueMessage = useStore(state => state.updateDialogueMessage);
    const syncDialogueToServer = useStore(state => state.syncDialogueToServer);
    const handleOpenAILLMAPIFetch = useStore(state => state.handleOpenAILLMAPIFetch);
    const onRefreshDialogue = useStore(state => state.onRefreshDialogue);
    // const [isEditing, setIsEditing] = useState(false);
    const [isHovering, setIsHovering] = useState(false);

    const isEditing = editingMessageIndex === index;
    const isEditingOtherMessage = editingMessageIndex !== null;

    const handleEditingTextAreaChange = (value) => {
        textareaRef.current.style.height = 'auto'; // 重置高度为内容物高度
        textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }

    const handleSaveMessage = () => {
        const value = { role: 'user', content: textareaRef.current.value }
        updateDialogueMessage(uuid, index, value);
        setEditingMessageIndex(null);
        syncDialogueToServer(uuid);
    }

    useEffect(() => {
        if (isEditing) {
            textareaRef.current.style.height = 'auto'; // 重置高度为内容物高度
            textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
        }
    }, [isEditing])

    const actionBarVisibility = (isHovering && !isEditing) ? true : false;

    const handleOnClickRefreshButton = () => {
        onRefreshDialogue(uuid, index);
        handleOpenAILLMAPIFetch(uuid);
    }

    return (
        <div className="user-message-block"
            onMouseMove={() => setIsHovering(true)}
            onMouseLeave={() => setIsHovering(false)}>
            <div className="user-message-bubble"
                style={{
                    width: isEditing && '100%',
                    backgroundColor: isEditing && '#424242',
                }}>
                {/* {content} */}
                {!isEditing && content}
                {isEditing &&
                    <div className="user-message-bubble-editing">
                        <textarea
                            ref={textareaRef}
                            defaultValue={content}
                            onChange={(e) => handleEditingTextAreaChange(e.target.value)}>
                        </textarea>
                        <div>
                            <button onClick={() => (setEditingMessageIndex(null))}>Cancel</button>
                            <button onClick={handleSaveMessage} style={{ backgroundColor: '#f9f9f9', color: '#0d0d0d' }}>Save</button>
                        </div>
                    </div>
                }
            </div>

            <div className="dialogue-panel-message-action-bar" style={{ marginTop: '8px', visibility: !actionBarVisibility && 'hidden', opacity: actionBarVisibility ? 1 : 0 }}>
                <div onClick={handleOnClickRefreshButton}   ><RefreshOutlinedIcon fontSize="small" /></div>
                <div onClick={() => setEditingMessageIndex(index)}   ><EditOutlinedIcon fontSize="small" /></div>
                <div onClick={() => handleCopyMessage(content)}><ContentCopyOutlinedIcon fontSize="" /></div>
                <div onClick={() => { if (!isEditingOtherMessage) handleDeleteMessage(index) }}><DeleteOutlinedIcon fontSize="small" /></div>
            </div>
        </div>
    );
};

const FetchingDialogue = memo(({ dialogue }) => {
    // console.log('FetchingDialogue');
    const currentDialogueUUID = useStore(state => state.currentDialogueUUID);
    const fetchingDialogue = useStore(state => state.fetchingDialogue[currentDialogueUUID]);

    if (!fetchingDialogue) return;

    // const content = "123";
    return (
        <div className="assistant-message-block" >
            <div>
                {/* <div>{fetchingDialogue}</div> */}
                <MarkdownRenderer content={fetchingDialogue} />
                <div className="assistant-message-dialogue-actions">
                    {/* <div onClick={() => {handleDeleteMessage(content)}}>delete</div>
                    <div onClick={() => {handleDeleteMessage  (content)}}>copy</div> */}
                </div>

            </div>
        </div>
    );
});




const DialoguePanel = ({ uuid, dialogue }) => {
    // console.log('DialoguePanel');
    const deleteDialogueMessage = useStore(state => state.deleteDialogueMessage)
    const syncDialogueToServer = useStore(state => state.syncDialogueToServer)

    const [editingMessageIndex, setEditingMessageIndex] = useState(null);

    useEffect(() => {
        if (editingMessageIndex !== null) setEditingMessageIndex(null);
    }, [uuid])

    const handleDeleteMessage = async (messageIndex) => {
        deleteDialogueMessage(uuid, messageIndex);
        syncDialogueToServer(uuid);
    }

    const handleCopyMessage = async (targetMessage) => {
        // console.log(targetMessage);

        navigator.clipboard.writeText(targetMessage).then(() => {
            // console.log('文本已成功复制到剪贴板！');
        }).catch(err => {
            console.error('复制失败: ', err);
        });
    }

    if (!dialogue) {
        return
    }

    return (
        <div className='dialogue-panel'>
            {dialogue.dialogue_content_json.map((message, index) => {

                if (message.role === 'user') {
                    return <UserMessage key={index} index={index} content={message.content} handleDeleteMessage={handleDeleteMessage} handleCopyMessage={handleCopyMessage}
                        uuid={uuid} editingMessageIndex={editingMessageIndex} setEditingMessageIndex={setEditingMessageIndex} />;
                }
                if (message.role === 'assistant') {
                    return <AssistantMessage key={index} index={index} content={message.content} handleDeleteMessage={handleDeleteMessage} handleCopyMessage={handleCopyMessage} editingMessageIndex={editingMessageIndex} />;
                }
                return null; // 处理其他角色的情况
            })}
            <FetchingDialogue />
        </div>

    );
};

export default DialoguePanel;